package com.ai.web.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.ai.web.cache.Constants;
import com.ai.web.cache.UserContext;
import com.ai.web.controller.BaseController;

public class BaseInterceptor  extends HandlerInterceptorAdapter{  
    
	private static Logger logger = Logger.getLogger(BaseInterceptor.class);
	
	@Override  
    public boolean preHandle(HttpServletRequest request,  
            HttpServletResponse response, Object handler) throws Exception {  
        
		HandlerMethod hm = (HandlerMethod) handler;
		Object bean = hm.getBean();
		if (bean instanceof BaseController) {
			BaseController bc = (BaseController) bean;
			bc.setRequest(request);
			bc.setResponse(response);
		}
		
		//logger.info("request Uri:" + request.getRequestURI() + " queryString:" + request.getQueryString());
		
		String reqUri = request.getRequestURI();
		Object obj = request.getSession().getAttribute(Constants.USER_CONTEXT);
		
		if (reqUri.endsWith("/login/in")) {
			
			String username = request.getParameter("username");
			//logger.info("[login] user=" + username);
			
			return true;
		} else if (reqUri.endsWith("/login/out")){
			
			if (obj != null) {
				UserContext uc = (UserContext) obj;
				String username = uc.getBgUser().getUsername();
				//logger.info("[logout] user=" + username);
			} else {
				//logger.info("[logout] session null.");
			}
			return true;
		} 
		else {
			if (obj == null) {
				request.getRequestDispatcher("/login/out").forward(request, response);
				return false;
			} else {
				return true;
			}
		}
		
    }  
}  

